<?php
namespace Frieza\Modules\Push\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\service\Push\PushService;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\tools\Log;

class NotifyController extends Controller
{
    public function index(Request $request,Content $content)
    {
        $tab = new Tab();
        $form = new Form();

        $form->html("<a href='https://metabase.haohaozhu.me/question/5325' target='_blank' style='color: #337ab7;font-weight: bold;font-size: 18px;'>推送结果查询</a>");
        $form->divider();
        $form->text('uid', 'UID')->required();
        $form->text('push_title', '标题');
        $form->textarea('push_content','内容')->required();
        $form->divider();
        $form->multiLinkSelect("link", '链接');
        $form->number("template_id", '通知模板ID')->default(0)->help("可选，私信等系统消息可填");
        $form->text('push_time', '推送时间')->help("可选，用于测试推送规则");

        $form->action(url('admin/push/notify/send'));

        $tab->add("推送", $form->render(), true);
        return $content
            ->header('创建推送')
            ->description(' ')
            ->breadcrumb(['text' => '创建推送'])
            ->row($tab);
    }

    public function send(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $data = [];
            $data['uid'] = $params['uid'];
            $data['title'] = $params['push_title'];
            $data['alert'] = $params['push_content'];
            $link = LinkFormat::generateLink($params['link']['link_type'], $params['link']['link_params'] ?? '');
            if ($link) {
                $data['param']['link'] = $link['app_template'];
            }
            $data['param']['push_id'] = "test_default_" . date("YmdHis");
            $data['param']['template_id'] = $params['template_id'];
            $push_time = $params['push_time'];
            if($push_time) {
                $data['param']['channel'] = PushService::getRuleByType('test', $push_time);
            }

            $result = PushService::send($data);
            if ($result) {
                $success = new MessageBag([
                    'title'   => '推送成功',
                ]);
                return redirect(url('/admin/push/notify'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '推送失败，请稍后重试'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '推送失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }
}
